<template>
  <div>
    <div u="bg-#f7f8fA pt-25px px-5">
      <el-form inline>
        <el-form-item label="消息内容">
          <el-input
            v-model="form.message"
            placeholder="消息内容"
            clearable
            class="u-w-180px!"
          />
        </el-form-item>

        <el-form-item label="消息类型">
          <el-select
            v-model="form.sendType"
            placeholder="消息类型"
            clearable
          >
            <el-option
              v-for="key in Object.keys(typeMap)"
              :key="key"
              :value="key"
              :label="typeMap[key]"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="消息状态">
          <el-select
            v-model="form.status"
            placeholder="消息状态"
            clearable
          >
            <el-option
              label="未读"
              :value="0"
            />
            <el-option
              label="已读"
              :value="1"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="发布时间">
          <el-date-picker
            v-model="form.range"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="search"
          >
            搜索
          </el-button>
          <el-button @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div u="flex items-center mt-4">
      <el-checkbox
        v-model="selectAll"
        @change="changeAll"
      >
        当页全选
      </el-checkbox>
      <el-button
        u="ml-10px"
        type="primary"
        :disabled="!msgStore.unRead"
        @click="readAll"
      >
        全部已读
      </el-button>
      <el-button
        :disabled="!chooseList.length"
        @click="readChoose"
      >
        批量已读
      </el-button>
    </div>

    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="list"
      header-cell-class-name="table-header"
      u-mt-5
      @selection-change="changeChooseList"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column label="消息内容">
        <template #default="{row}">
          <div u-line-clamp-2>
            {{ getMessage(row.message) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        width="200"
        label="消息类型"
      >
        <template #default="{row}">
          {{ getMsgType(row.sendType) }}
        </template>
      </el-table-column>
      <el-table-column
        width="100"
        label="消息状态"
      >
        <template #default="{ row }">
          {{ getStatus(row.status) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        width="180"
        label="发布时间"
      />

      <el-table-column
        label="操作"
        width="100"
      >
        <template #default="{ row }">
          <div
            u="text-primary cursor-pointer"
            @click="goDetail(row)"
          >
            查看
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="list.length"
      u-mt-4
      :current-page="current"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="changeSize"
      @current-change="changePage"
    />
  </div>
</template>

<script setup>
import { useMessageStore } from '@/stores/message'
const list = ref([])
const form = ref({})
const loading = ref(false)
const chooseList = ref([])

const msgStore = useMessageStore()

const getParams = () => {
  const { range, message, status, sendType } = form.value
  const params = {
    current: current.value,
    size: size.value,
    message,
    status,
    sendType
  }
  if (range) {
    const [startTime, endTime] = range
    params.startTime = startTime
    params.endTime = endTime
  }
  return params
}

const fetchList = async () => {
  loading.value = true
  try {
    const res = await http({
      url: http.adornUrl('/platform/notifyLog/pageByNotifyLogParam'),
      params: http.adornParams(getParams())
    })
    list.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.log('%c Line:53 🥛 error', 'color:#CB9C1A', error)
  }
  loading.value = false
}

const { current, size, changePage, changeSize, total } = usePagination(fetchList)
fetchList()

const getMessage = msg => {
  if (msg) {
    const res = JSON.parse(msg) || {}
    return res.message
  }
  return ''
}

const typeMap = {
  21: '完善价格信息通知',
  22: '新询价通知',
  23: '确认报价通知',
  24: '询价单逾期通知',
  25: '询价单取消通知',
  26: '新采购订单通知',
  27: '采购订单支付成功通知',
  28: '采购订单退款通知',
  29: '采购订单退货通知',
  30: '采购订单确认收货通知'
}

const getMsgType = type => {
  return typeMap[type]
}

const getStatus = status => {
  const list = ['未读', '已读']
  return list[status]
}

const router = useRouter()

const goDetail = (row) => {
  const { sendType, message } = row
  const msg = JSON.parse(message)
  const { orderNo, platformOrderNumber } = msg
  setIsRead([row.logId], 0)
  if (sendType >= 21 && sendType <= 25) {
    router.push({
      path: '/self/inquiry/detail',
      query: {
        orderNo
      }
    })
  } else if ([27, 28].includes(sendType)) {
    router.push({
      path: '/self/order-refund/index',
      query: {
        orderNumber: orderNo
      }
    })
  } else {
    router.push({
      path: '/self/order/index',
      query: {
        platformOrderNumber
      }
    })
  }
}

const search = () => {
  current.value = 1
  fetchList()
}

const reset = () => {
  form.value = {}
  current.value = 1
  fetchList()
}

const setIsRead = async (ids, type) => {
  const params = {
    type
  }
  if (type == 0) {
    params.logIds = ids
  }
  await http({
    url: http.adornUrl('/platform/notifyLog/is_read'),
    method: 'post',
    data: http.adornData(params)
  })

  fetchList()
  msgStore.updateCount()
}

const changeChooseList = list => {
  chooseList.value = list
}

const readAll = () => {
  setIsRead(null, 1)
}

const readChoose = async () => {
  const ids = chooseList.value.map(item => item.logId)
  await setIsRead(ids, 0)
  // eslint-disable-next-line require-atomic-updates
  chooseList.value = []
  selectAll.value = false
}

const tableRef = ref()
const selectAll = ref(false)
const changeAll = val => {
  if (val) {
    list.value.forEach(item => {
      tableRef.value.toggleRowSelection(item, true)
    })
  } else {
    tableRef.value.clearSelection()
  }
}
</script>
